package com.api.workflow.web;

import com.api.workflow.util.YNHttpUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import weaver.common.util.string.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * MMI001    需求计划创建/变更【OA-》SAP】
 *
 * */
public class YNMMI001Action extends BaseBean implements Action {
    public static void main(String[] args) {

    }

    @Override
    public String execute(RequestInfo requestInfo) {


        BaseBean baseBean = new BaseBean();
        String requestid = requestInfo.getRequestid();
        int formid = requestInfo.getRequestManager().getFormid();
        int formidAbs = Math.abs(formid);
        String tableName = "formtable_main_" + formidAbs;
        // 主表数据
        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
        Property[] property = mainTableInfo.getProperty();
        Map<String, Object> mainTableInfoMap = new HashMap<>();
        for (int i = 0; i < property.length; i++) {
            String name = property[i].getName().toLowerCase();
            mainTableInfoMap.put(name, Util.null2String(property[i].getValue()));
        }
        baseBean.writeLog("MMI001=======mainTableInfoMap:" + com.alibaba.fastjson.JSONObject.toJSONString(mainTableInfoMap));

        //明细表数据
        List<Map<String, Object>> detailTableMap = getMaps(requestInfo);
        baseBean.writeLog("=============YNMMI001Action:" + com.alibaba.fastjson.JSONObject.toJSONString(detailTableMap));
        writeLog("start------------------------YNMMI001Action");
        //获得流程id
        String workflowid = requestInfo.getWorkflowid();
        //获取表id
        writeLog("start------------------------YNMMI001Action" + requestid);
        RecordSet rs = new RecordSet();
        rs.execute("select tablename from workflow_base a,workflow_bill b where a.formid=b.id and a.id=" + workflowid);
        rs.next();
        //获取主表名
        String maintable = Util.null2String(rs.getString("tablename"));

        //根据表id和主表名查找主表的相关信息
        rs.executeQuery("select * from " + maintable + " where requestid=?", new Object[]{requestid});
        rs.next();
        String sqrq = Util.null2String(rs.getString("sqrq"));//申请日期
        System.out.println(sqrq + "sqrqsqrqsqtr");
        //业务逻辑

        try {

            //主表数据
            JSONObject result = new JSONObject();

            result.put("zczlx", mainTableInfoMap.get("czlx"));
            if (mainTableInfoMap.get("czlx").equals("C")) {
                result.put("pbdnr", mainTableInfoMap.get("lcbh"));
            } else {
                result.put("pbdnr", detailTableMap.get(0).get("xzxqjh"));
            }
            if (StringUtil.isNullOrEmpty(sqrq)) {
                sqrq = (String) mainTableInfoMap.get("sqrq");
            }

            result.put("ztype", mainTableInfoMap.get("jhlx"));
            result.put("zreqptmt", mainTableInfoMap.get("xqbm"));
            result.put("zplancat", mainTableInfoMap.get("jhlb"));
            result.put("werks", mainTableInfoMap.get("jhgc"));
            String r1r4llcg = String.valueOf(mainTableInfoMap.get("r1r4llcg"));
            if (r1r4llcg.equals("0")) {
                result.put("ZSFLL", "X");
            } else {
                result.put("ZSFLL", "");
            }


            result.put("zcname", mainTableInfoMap.get("lxr"));

            RecordSet recordSet4 = new RecordSet();
            recordSet4.executeQuery("select * from hrmResource where id=?", mainTableInfoMap.get("sqr"));
            recordSet4.next();
            String lastname4 = Util.null2String(recordSet4.getString("lastname"));
            result.put("afnam", lastname4);
            result.put("ztelf1", mainTableInfoMap.get("lxdh"));

            //明细表数据
            JSONArray item = new JSONArray();

            int count = 10;
            for (int i = 0; i < detailTableMap.size(); i++) {
                Map<String, Object> map = detailTableMap.get(i);

                JSONObject ITEM = new JSONObject();
                ITEM.put("zxmh", count);
                count = count + 10;
                ITEM.put("matnr", map.get("wlbh"));
                ITEM.put("maktx", map.get("wlms"));
                ITEM.put("amount", map.get("xqsl"));
                ITEM.put("meins", map.get("jldw"));
                ITEM.put("zrequdate", map.get("xqrq"));
                ITEM.put("zdate", sqrq);
                ITEM.put("zmemo", map.get("bz"));
                RecordSet recordSet3 = new RecordSet();
                recordSet3.executeQuery("select * from hrmResource where id=?", map.get("tbr"));
                recordSet3.next();
                String lastname3 = Util.null2String(recordSet3.getString("lastname"));
                ITEM.put("zuser", lastname3);
                ITEM.put("kostl", map.get("cbzx"));
                ITEM.put("anln1", map.get("gdzc"));
                ITEM.put("aufnr", map.get("nbdd"));
                ITEM.put("ekgrp", map.get("cgz"));
                ITEM.put("ZSFJJ", map.get("sfjj"));
                ITEM.put("matkl", map.get("wlz"));
                //新加字段是否紧急
                ITEM.put("ZSFJJ", map.get("sfjj"));

                item.add(ITEM);

            }

            result.put("item", item);
            baseBean.writeLog("wyq===MMI001需求计划创建/变更接口===result" + result.toString());
            String post = YNHttpUtils.MMI001(result.toString(), YNHttpUtils.token());

            baseBean.writeLog("wyq===MMI001需求计划创建/变更接口===post" + post);

            JSONObject jsonObject = JSONObject.parseObject(post);

            String type = jsonObject.getString("type");
            String message = jsonObject.getString("message");
            String banfn = jsonObject.getString("banfn");
            JSONArray item2 = jsonObject.getJSONArray("item");
            StringBuilder message1 = new StringBuilder();
            if (item2.size() != 0) {
                for (int i = 0; i < item2.size(); i++) {
                    JSONObject jsonObject1 = item2.getJSONObject(i);
                    if (jsonObject1.get("type").equals("E")) {
                        message1.append(jsonObject1.get("message")).append(";");
                    }
                }
            }
            baseBean.writeLog("banfnbanfnbanfn" + banfn);
            if (StringUtil.isNullOrEmpty(banfn)) {
                banfn = null;
            }
            RecordSet recordSet = new RecordSet();
            String updateMainTableName = "update " + tableName + " set  qqcsx = ? , fhjgx = ?,cgsqbh=?  where  requestid = ? ";
            recordSet.executeUpdate(updateMainTableName, result.toString(), post, banfn, requestid);


            if (!"S".equals(type)) {
                requestInfo.getRequestManager()
                        .setMessageid(requestInfo.getRequestid() + "OA-MMI001需求计划创建/变更接口");
                requestInfo.getRequestManager().setMessagecontent("SAP接口异常，请联系SAP人员，错误信息提示:" + message1);
                return Action.FAILURE_AND_CONTINUE;

            }
            JSONArray item1 = jsonObject.getJSONArray("item");
            for (int i = 0; i < item1.size(); i++) {
                JSONObject jsonObject1 = item1.getJSONObject(i);
                String zxmh = jsonObject1.getString("zxmh");//明细行号

                //查询主表id
                String mainid = "";
                String sql = "select * from " + tableName + " where requestid = '" + requestid + "'";
                rs.execute(sql);
                if (rs.next()) {
                    mainid = rs.getString("id");
                }

                //根据明细行号匹配明细
                for (int i1 = 0; i1 < item.size(); i1++) {
                    JSONObject map1 = item.getJSONObject(i1);
                    String zxmh1 = map1.get("zxmh").toString();
                    if (zxmh.equals(zxmh1)) {

                        String update = "update " + tableName + "_dt1 set xmxh = '" + zxmh + "' where mainid = '" + mainid + "'"
                                + " and wlbh = '" + map1.get("matnr") + "'"
                                + " and jldw = '" + map1.get("meins") + "'";

                        baseBean.writeLog("wyq============更新明细表" + update);
                        rs.executeUpdate(update);
                    }
                }
            }
        } catch (Exception e) {
            baseBean.writeLog("MMI001需求计划创建/变更接口=======requestid:" + requestid + "=======formid:" + formid + "=======tableName:" + tableName + "=======异常:" + e.toString());
            requestInfo.getRequestManager()
                    .setMessageid(requestInfo.getRequestid() + "OA-MMI001需求计划创建/变更接口");
            requestInfo.getRequestManager().setMessagecontent("接口异常" + e.toString());
        }


        return Action.SUCCESS;


    }


    /**
     * 提取明细表全部的数据
     *
     * @param requestInfo
     * @return
     */
    private static List<Map<String, Object>> getMaps(RequestInfo requestInfo) {
        DetailTable[] detailTable = requestInfo.getDetailTableInfo().getDetailTable();
        //这里是存储了全部的明细表数据  可自行修改存储结构
        List<Map<String, Object>> detailTableMap = new ArrayList<>();
        if (detailTable.length > 0) {
            for (int i = 0; i < detailTable.length; i++) {
                DetailTable dt = detailTable[i];
                Row[] s = dt.getRow();
                for (int j = 0; j < s.length; j++) {
                    Row r = s[j];
                    Cell c[] = r.getCell();
                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                    for (int k = 0; k < c.length; k++) {
                        Cell c1 = c[k];
                        String name = c1.getName().toLowerCase();
                        String value = c1.getValue();
                        objectObjectHashMap.put(name, value);
                    }
                    detailTableMap.add(objectObjectHashMap);
                }
            }
        }
        return detailTableMap;
    }

}
